// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System.ComponentModel;
using System.Threading;
using BrainTechLLC.ThreadSafeObjects;

namespace BrainTechLLC
{
    /// <summary>
    /// A collection of sequential changes to a single property on a uniquely identified business object / class
    /// </summary>
    public class PropertyChangeCollection<T> where T : new()
    {
        /// <summary>
        /// Stores the original property value.  Used when CancelUpdate is called to revert properties (quickly) back to their original values.
        /// </summary>
        public object _originalValue;

        public ThreadSafeList<PropertyChangeNotificationArgs> _propertyChanges = new ThreadSafeList<PropertyChangeNotificationArgs>();

        public PropertyDescriptor _propertyDescriptor = null;

        public string _propertyName;

        public object FinalValue
        {
            get { return _propertyChanges.GetLastItemInList(); }
        }

        /// <summary>
        /// Records a property change
        /// </summary>		
        public void RecordChange(PropertyChangeNotificationArgs changeArgs)
        {
            if (_originalValue == null)
            {
                Interlocked.CompareExchange<object>(ref _originalValue, changeArgs._previousValue, null);
                _propertyDescriptor = TypeDescriptor.GetProperties(typeof(T))[changeArgs.PropertyName];
                _propertyName = changeArgs.PropertyName;
            }

            _propertyChanges.Add(changeArgs);
        }

        public void Reset()
        {
            _propertyChanges.Clear();
            _originalValue = null;
        }
    }
}